package com.quectel.core.module.scheduling.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quectel.constant.core.scheduling.SchedulingApplyConstants;
import com.quectel.constant.core.scheduling.SchedulingLeaveConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.ex.schedulingapply.SchedulingLeaveBanlancException;
import com.quectel.core.module.scheduling.dao.SchedulingLeaveBalanceDao;
import com.quectel.core.module.scheduling.dto.SchedulingLeaveBalanceDto;
import com.quectel.core.module.scheduling.dto.SchedulingLeaveBalanceLogDto;
import com.quectel.core.module.scheduling.dto.SchedulingLeaveConfigDto;
import com.quectel.core.module.scheduling.entity.SchedulingLeaveBalanceEntity;
import com.quectel.core.module.scheduling.service.SchedulingLeaveBalanceLogService;
import com.quectel.core.module.scheduling.service.SchedulingLeaveBalanceService;
import com.quectel.core.module.scheduling.service.SchedulingLeaveConfigService;
import com.quectel.core.module.schedulingapply.dto.vo.SchedulingBalanceTimeVO;
import com.quectel.core.module.schedulingapply.dto.vo.SchedulingTimeVO;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import com.quectel.util.spring.SpringUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/07/05 13:24
 */
@DubboService
public class SchedulingLeaveBalanceServiceImpl extends ServiceImpl<SchedulingLeaveBalanceDao, SchedulingLeaveBalanceEntity> implements SchedulingLeaveBalanceService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SchedulingLeaveBalanceServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> SCHEDULING_LEAVE_BALANCE_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "SCHEDULING_LEAVE_BALANCE_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<SchedulingLeaveBalanceDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(SCHEDULING_LEAVE_BALANCE_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private SchedulingLeaveBalanceDao schedulingLeaveBalanceDao;
    @Autowired
    private SchedulingLeaveBalanceLogService schedulingLeaveBalanceLogService;
    @Autowired
    private SchedulingLeaveConfigService schedulingLeaveConfigService;


    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.SCHEDULING_LEAVE_BALANCE_LOCK + "#{#personId}"
            }
    )
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateBalance(Long personId, Byte sourceType, Long sourceId, Long balanceId, BigDecimal num, Byte unit) {
        //根据personId type 和 sourceId查询 如果有则不更新
        List<SchedulingLeaveBalanceLogDto> schedulingLeaveBalanceLogDtos = schedulingLeaveBalanceLogService.selectByPersonAndSourceAndBalance(personId, sourceType, sourceId, balanceId);
        if (CollectionUtils.isNotEmpty(schedulingLeaveBalanceLogDtos)) {
            //不再继续操作
            return;
        }

        SchedulingApplyConstants.BalanceTypeEnum byType = SchedulingApplyConstants.BalanceTypeEnum.getByType(sourceType);
        if (byType == null) {
            return;
        }
        //生成新的
        SchedulingLeaveBalanceLogDto schedulingLeaveBalanceLogDto = new SchedulingLeaveBalanceLogDto();
        schedulingLeaveBalanceLogDto.setPersonId(personId);
        schedulingLeaveBalanceLogDto.setBalanceId(balanceId);
        schedulingLeaveBalanceLogDto.setSourceType(sourceType);
        schedulingLeaveBalanceLogDto.setSourceId(sourceId);
        schedulingLeaveBalanceLogDto.setNum(num);
        schedulingLeaveBalanceLogDto.setUnit(unit);
        schedulingLeaveBalanceLogDto.setLogDate(new Date());
        schedulingLeaveBalanceLogDto.setCreateTime(new Date());
        schedulingLeaveBalanceLogService.save(schedulingLeaveBalanceLogDto);

        //更新余额
        SchedulingLeaveBalanceDto dto = selectById(balanceId);
        if (dto == null) {
            throw new SchedulingLeaveBanlancException("没有找到可处理的余额");
        }
        SchedulingLeaveConfigDto schedulingLeaveConfigDto = schedulingLeaveConfigService.selectById(dto.getLeaveId());

        BigDecimal timeLength = SchedulingLeaveConstants.TimeUnitEnum.changeUnit(num, unit, dto.getUnit());
        //如果是加班转余额 则需要处理的是总额度
        if (SchedulingApplyConstants.BalanceTypeEnum.OVERTIME_CONVERTED_TO_BALANCE.equals(byType)
                || SchedulingApplyConstants.BalanceTypeEnum.AUTO_GRANT.equals(byType)) {
            BigDecimal balance = dto.getBalance();
            if (balance == null) {
                balance = BigDecimal.ZERO;
            }

            if (byType.getIsPositive().equals(SystemConstants.YES)) {
                balance = balance.add(timeLength);
            } else {
                balance = balance.subtract(timeLength);
            }

            //取整规则
            if(schedulingLeaveConfigDto!=null && schedulingLeaveConfigDto.getGrantRule()!=null){
                SchedulingLeaveConstants.RoundingRuleEnum roundingRuleEnum = SchedulingLeaveConstants.RoundingRuleEnum.getByType(schedulingLeaveConfigDto.getGrantRule().getRoundingRule());
                if (roundingRuleEnum != null) {
                    BigDecimal roundValue = SchedulingLeaveConstants.RoundingRuleEnum.getRoundValue(roundingRuleEnum, balance);
                    dto.setBalance(roundValue);
                }
            }else {
                //取整规则
                dto.setBalance(balance);
            }

        } else if (SchedulingApplyConstants.BalanceTypeEnum.APPLY.equals(byType)
                || SchedulingApplyConstants.BalanceTypeEnum.DAILY_CAL_UPDATE.equals(byType)
        ) {
            //如果是申请或者计算回收
            BigDecimal usedBalance = dto.getUsedBalance();
            if (usedBalance == null) {
                usedBalance = BigDecimal.ZERO;
            }
            if (byType.getIsPositive().equals(SystemConstants.YES)) {
                usedBalance = usedBalance.add(timeLength);
            } else {
                usedBalance = usedBalance.subtract(timeLength);
            }

            //取整规则
            if(schedulingLeaveConfigDto!=null && schedulingLeaveConfigDto.getGrantRule()!=null){
                SchedulingLeaveConstants.RoundingRuleEnum roundingRuleEnum = SchedulingLeaveConstants.RoundingRuleEnum.getByType(schedulingLeaveConfigDto.getGrantRule().getRoundingRule());
                if (roundingRuleEnum != null) {
                    BigDecimal roundValue = SchedulingLeaveConstants.RoundingRuleEnum.getRoundValue(roundingRuleEnum, usedBalance);
                    dto.setUsedBalance(roundValue);
                }
            }else {
                //取整规则
                dto.setUsedBalance(usedBalance);
            }
        }
        SchedulingLeaveBalanceService schedulingLeaveBalanceService = SpringUtils.getBean(SchedulingLeaveBalanceService.class);
        schedulingLeaveBalanceService.updateById(dto);
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.SCHEDULING_LEAVE_BALANCE_LOCK + "#{#personId}"
            }
    )
    @Transactional(rollbackFor = RuntimeException.class)
    public void rollBackBalance(Long personId, Byte sourceType, Long sourceId) {
        //根据personId type 和 sourceId查询 如果有则不更新
        List<SchedulingLeaveBalanceLogDto> schedulingLeaveBalanceLogDtos = schedulingLeaveBalanceLogService.selectByPersonAndSource(personId, sourceType, sourceId);
        if (CollectionUtils.isEmpty(schedulingLeaveBalanceLogDtos)) {
            return;
        }
        for (SchedulingLeaveBalanceLogDto logDto : schedulingLeaveBalanceLogDtos) {
            SchedulingApplyConstants.BalanceTypeEnum byType = SchedulingApplyConstants.BalanceTypeEnum.getByType(logDto.getSourceType());
            if (byType == null) {
                return;
            }

            //更新余额
            SchedulingLeaveBalanceDto dto = selectById(logDto.getBalanceId());
            if (dto == null) {
                throw new SchedulingLeaveBanlancException("没有找到可处理的余额");
            }
            BigDecimal timeLength = SchedulingLeaveConstants.TimeUnitEnum.changeUnit(logDto.getNum(), logDto.getUnit(), dto.getUnit());
            //如果是加班转余额 则需要处理的是总额度
            if (SchedulingApplyConstants.BalanceTypeEnum.OVERTIME_CONVERTED_TO_BALANCE.equals(byType)
                    || SchedulingApplyConstants.BalanceTypeEnum.AUTO_GRANT.equals(byType)) {
                BigDecimal balance = dto.getBalance();
                if (balance == null) {
                    balance = BigDecimal.ZERO;
                }
                //反向更新
                if (!byType.getIsPositive().equals(SystemConstants.YES)) {
                    balance = balance.add(timeLength);
                } else {
                    balance = balance.subtract(timeLength);
                }
                dto.setBalance(balance);
            } else if (SchedulingApplyConstants.BalanceTypeEnum.APPLY.equals(byType)
                    || SchedulingApplyConstants.BalanceTypeEnum.DAILY_CAL_UPDATE.equals(byType)
            ) {
                //如果是申请或者计算回收
                BigDecimal usedBalance = dto.getUsedBalance();
                if (usedBalance == null) {
                    usedBalance = BigDecimal.ZERO;
                }
                //反向更新
                if (!byType.getIsPositive().equals(SystemConstants.YES)) {
                    usedBalance = usedBalance.add(timeLength);
                } else {
                    usedBalance = usedBalance.subtract(timeLength);
                }
                dto.setUsedBalance(usedBalance);
            }
            SchedulingLeaveBalanceService schedulingLeaveBalanceService = SpringUtils.getBean(SchedulingLeaveBalanceService.class);
            schedulingLeaveBalanceService.updateById(dto);
            //删除详情
            schedulingLeaveBalanceLogService.deleteById(logDto.getId());
        }

    }


    @Override
    public void leaveUsedBalanceUpdate(SchedulingTimeVO schedulingTimeVO, Byte updateType) {
        if (CollectionUtils.isEmpty(schedulingTimeVO.getBalanceTimes())) {
            return ;
        }
        List<SchedulingBalanceTimeVO> balanceTimes = schedulingTimeVO.getBalanceTimes();

        SchedulingLeaveBalanceService schedulingLeaveBalanceService = SpringUtils.getBean(SchedulingLeaveBalanceService.class);


        //1.校验
        for (SchedulingBalanceTimeVO balanceTime : balanceTimes) {
            SchedulingLeaveBalanceDto schedulingLeaveBalanceDto = schedulingLeaveBalanceService.selectById(balanceTime.getBalanceId());
            if (schedulingLeaveBalanceDto == null) {
                return ;
            }
        }
        //2.更新对应的余额
        for (SchedulingBalanceTimeVO balanceTime : balanceTimes) {
            SchedulingLeaveBalanceDto schedulingLeaveBalanceDto = schedulingLeaveBalanceService.selectById(balanceTime.getBalanceId());
            //2.1如果是扣减
            BigDecimal bigDecimal = SchedulingLeaveConstants.TimeUnitEnum.changeUnit(balanceTime.getRestBalance(), balanceTime.getUnit(), schedulingLeaveBalanceDto.getUnit());
            BigDecimal multiply;
            if (SystemConstants.NORMAL.equals(updateType)) {
                multiply = schedulingLeaveBalanceDto.getUsedBalance().multiply(bigDecimal);
            } else {
                //2.1.1如果是补发
                multiply = schedulingLeaveBalanceDto.getUsedBalance().add(bigDecimal);
            }
            schedulingLeaveBalanceDto.setUsedBalance(multiply);
            schedulingLeaveBalanceService.updateById(schedulingLeaveBalanceDto);
        }

    }




    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveOrUpdateBatch(List<SchedulingLeaveBalanceDto> schedulingLeaveBalanceDtos) {
        List<SchedulingLeaveBalanceDto> saveList = schedulingLeaveBalanceDtos.stream().filter(schedulingLeaveBalanceDto -> schedulingLeaveBalanceDto.getId() == null).collect(Collectors.toList());
        List<SchedulingLeaveBalanceDto> updateList = schedulingLeaveBalanceDtos.stream().filter(schedulingLeaveBalanceDto -> schedulingLeaveBalanceDto.getId() != null).collect(Collectors.toList());

        List<SchedulingLeaveBalanceEntity> saveEntityList = CopyUtils.copyList(saveList, SchedulingLeaveBalanceEntity.class);
        for (SchedulingLeaveBalanceEntity entity : saveEntityList) {
            entity.setId(Snowflake.nextId());
        }
        if(CollectionUtils.isNotEmpty(saveList)){
            super.saveOrUpdateBatch(saveEntityList);
        }

        SchedulingLeaveBalanceService schedulingLeaveBalanceService = SpringUtils.getBean(SchedulingLeaveBalanceService.class);
        for (SchedulingLeaveBalanceDto dto : updateList) {
            schedulingLeaveBalanceService.updateById(dto);
        }

    }

    @Override
    public SchedulingLeaveBalanceDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                SCHEDULING_LEAVE_BALANCE_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public SchedulingLeaveBalanceDto selectById(Long id) {
        SchedulingLeaveBalanceEntity entity = schedulingLeaveBalanceDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, SchedulingLeaveBalanceDto.class));
    }

    @Override
    public List<SchedulingLeaveBalanceDto> queryList(Map<String, Object> params) {
        List<SchedulingLeaveBalanceEntity> list = schedulingLeaveBalanceDao.queryList(params);
        List<SchedulingLeaveBalanceDto> result = CopyUtils.copyList(list, SchedulingLeaveBalanceDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    @Override
    public List<SchedulingLeaveBalanceDto> queryListWithoutPadding(Map<String, Object> params) {
        List<SchedulingLeaveBalanceEntity> list = schedulingLeaveBalanceDao.queryList(params);
        return CopyUtils.copyList(list, SchedulingLeaveBalanceDto.class);
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private SchedulingLeaveBalanceDto paddingField(SchedulingLeaveBalanceDto dto) {
        if (dto != null) {

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return schedulingLeaveBalanceDao.queryTotal(params);
    }

    @Override
    public Long save(SchedulingLeaveBalanceDto dto) {
        SchedulingLeaveBalanceEntity entity = CopyUtils.copyObj(dto, SchedulingLeaveBalanceEntity.class);
        entity.setId(Snowflake.nextId());
        schedulingLeaveBalanceDao.insert(entity);
        return entity.getId();
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.SCHEDULING_LEAVE_BALANCE_LOCK + "#{#dto.personId}"
            }
    )
    public void updateById(SchedulingLeaveBalanceDto dto) {
        SchedulingLeaveBalanceEntity entity = CopyUtils.copyObj(dto, SchedulingLeaveBalanceEntity.class);

        schedulingLeaveBalanceDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.SCHEDULING_LEAVE_BALANCE_LOCK + "#{#dot.personId}"
            }
    )
    public void updateAllColumnById(SchedulingLeaveBalanceDto dto) {
        SchedulingLeaveBalanceEntity entity = CopyUtils.copyObj(dto, SchedulingLeaveBalanceEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, schedulingLeaveBalanceDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        schedulingLeaveBalanceDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
